package yc.bluetooth.libvoice.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.speech.tts.Voice;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.bluetoothlibrary.bluetooth.BTBluetooth;
import com.example.bluetoothlibrary.bluetooth.OnConnectListener;
import com.example.bluetoothlibrary.bluetooth.OnSearchListener;
import com.example.bluetoothlibrary.broadcastreceiver.BluetoothBroadcastReceiver;
import com.example.bluetoothlibrary.listener.OnBindStateChangeListener;
import com.example.bluetoothlibrary.listener.OnBluetoothStateChangeListener;
import com.example.bluetoothlibrary.model.SearchDevice;
import com.example.bluetoothlibrary.utils.TypeConversion;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.util.Arrays;
import java.util.List;

import yc.bluetooth.libvoice.Cons;
import yc.bluetooth.libvoice.play.VoicePlay;
import yc.bluetooth.libvoice.util.FileUtil;
import yc.bluetooth.libvoice.util.HandlerUtil;
import yc.bluetooth.libvoice.util.PcmToWavUtil;
import yc.bluetooth.libvoice.util.ServerClientUtil;
import yc.bluetooth.libvoice.util.TimeUtil;
import yc.bluetooth.voicecontrol.MyJni;

/**
 * 语音遥控器  语音数据走自定义服务的通道
 * 1、接收语音数据
 * 2、语音数据解码
 * 3、播放语音数据
 *
 * 遥控器固件处理：固件与手机连接成功就修改了MTU，无需手机端申请
 */
public class VoiceService extends Service {
    private static final String TAG = VoiceService.class.getSimpleName();

    //通知遥控器语音数据切换走GATT发送给手机
    private static final byte[] CHANGE_HID_GATT = new byte[]{0x01};
    //语音数据接收开始标志、结束标志
    private static final byte[] VOICE_RECEIVE_START = new byte[]{0x01};
    private static final byte[] VOICE_RECEIVE_END = new byte[]{0x00};

    private Messenger serviceMessenger;  //Service中的Messenger
    private Messenger clientMessenger;   //存储客户端中传递过来的Messenger

    private BTBluetooth btBluetooth;
    private BluetoothDevice curBluetoothDevice;
    private boolean isConnected = false;   //连接状态
    private boolean isBounded = false;     //配对状态
    private boolean isAppDisConnect = false;  //是否是APP主动断开
    private boolean isAppDisBound = false;    //是否是APP主动解除配对
    private boolean isSysBtClose = false;     //是否是系统蓝牙断开，导致配对设备解除配对，GATT自然也就断开
    private boolean isStartVoiceOk = false;   //是否可以开启语音数据接收

    private int packetMaxLen;

    private VoicePlay voicePlay;  //播放音频
    private String voiceDirectoryPath;  //语音目录路径   PATH_LOCAL/时间+voices
    private String voiceTxtFilePath;   //语音.txt文件路径
    private String voicePcmFilePath;   //语音.pcm文件路径
    private String voiceWavFilePath;   //语音.wav文件路径
    private File voiceTxtFile;    //语音.txt文件
    private File voicePcmFile;    //语音.pcm文件
    private File voiceWavFile;    //语音.wav文件

    //已取消，用于在.so库中
    private String preVoicePcmFilePath;   //语音.pcm文件路径(之前pcm文件)
    private File preVoicePcmFile;    //语音.pcm文件

    /**
     * 定义一个Handler,用于处理客户端发来的请求
     */
    @SuppressLint("HandlerLeak")
    private Handler serviceHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.replyTo == null) {
                Log.e(TAG, "ServiceHandler:handleMessage() msg.replyTo == null");
                return;
            }
            //获取客户端中传递过来的Messenger
            clientMessenger = msg.replyTo;

            switch (msg.what) {
                case Cons.MSG_INIT_BLUETOOTH:  //初始化蓝牙 蓝牙模式  true - BLE , false - bt3.0
                    boolean btType = (boolean) msg.obj;
                    Log.d(TAG, "service receive from client: To Init Bluetooth...btType = " + btType);
                    initBluetooth(btType);
                    break;

                case Cons.MSG_SCAN:  //扫描设备
                    Log.d(TAG, "service receive from client: To Scan Device...");
                    scanDevice();
                    break;

                case Cons.MSG_STOP_SCAN:  //停止扫描
                    Log.d(TAG, "service receive from client: To Stop Scan ...");
                    stopScanDevice();
                    break;

                case Cons.MSG_PAIR_CONNECT: //配对连接设备
                    initParams();
                    curBluetoothDevice = (BluetoothDevice) msg.obj;
                    Log.d(TAG, "service receive from client: To Pair and Connect Device ...device.address = " + curBluetoothDevice.getAddress());
                    if (curBluetoothDevice == null) {
                        //通知客户端目标设备为空
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "当前设备不存在！");
                        return;
                    }

                    //1、先配对，配对成功后，再去连接
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "配对连接设备...", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);
                    pairDevice(curBluetoothDevice);
                    break;

                case Cons.MSG_DIS_PAIR_DISCONNECT:  //断开连接，解除配对
                    disConnectDevice();
                    break;

                case Cons.MSG_START_VOICE:  //开始接收语音数据、解码播报
                    if (isStartVoiceOk) {
                        //已准备好接收语音数据

                    } else {
                        //通知客户端无法接收语音数据
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "无法接收语音数据");
                    }
                    break;
            }
        }
    };

    //处理本Service中的事务
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case Cons.HANDLER_BT_CLOSED:  //蓝牙已关闭
                    //配对过程中蓝牙关闭，移除配对超时
                    mHandler.removeCallbacks(pairRunnable);
                    isSysBtClose = true;
                    // 向客户端发送 系统蓝牙已关闭
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "系统蓝牙已关闭");
                    break;

                case Cons.HANDLER_BT_OPENED:  //蓝牙已打开
                    isSysBtClose = false;
                    // 向客户端发送 系统蓝牙已打开
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "系统蓝牙已打开", Cons.UI_STRING_NOTIFY_LEVEL_INFO);
                    break;

                case Cons.HANDLER_PAIR_SUCCESS:  //配对成功
                    //移除配对超时
                    mHandler.removeCallbacks(pairRunnable);
                    // 向客户端发送 设备已配对成功
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "设备已配对", Cons.UI_STRING_NOTIFY_LEVEL_INFO);
                    //2、去连接设备
                    connectDevice(curBluetoothDevice);
                    break;

                case Cons.HANDLER_DIS_PAIR_SUCCESS:  //解除配对
                    //移除配对连接超时
                    mHandler.removeCallbacks(pairRunnable);
                    if (isAppDisBound) {  //APP主动解除配对
                        isAppDisBound = false;
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_PAIR_CONNECT_STATE,false);

                    } else {  // 系统蓝牙断开解除配对
                        // 向客户端发送 设备已解除配对
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "设备已解除配对");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_PAIR_CONNECT_STATE,false);
                    }
                    break;

                case Cons.HANDLER_CONNECT_SUCCESS:  //连接成功
                    // 向客户端发送 连接成功
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_PAIR_CONNECT_STATE,true);
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "连接成功", Cons.UI_STRING_NOTIFY_LEVEL_INFO);
                    //发送01数据，通知遥控器语音数据切换走GATT发送给手机
                    Log.d(TAG, "发送01...");
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "发送01...", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);
                    sendMsgToDevice(CHANGE_HID_GATT);
                    break;

                case Cons.HANDLER_DISCONNECT_SUCCESS: //断开连接
                    //先断开连接，再解除配对
                    disPairDevice(curBluetoothDevice);
                    break;

                case Cons.HANDLER_SEND_CHANGE_HID_GATT_SUCCESS:  //发送01成功
                    //可以准备接收语音数据
                    isStartVoiceOk = true;
                    break;

                case Cons.HANDLER_RECEIVE_FLAG_SUCCESS:  //接收语音开始、结束标志
                    byte[] flagBuffer = (byte[]) msg.obj;
                    String flag = TypeConversion.bytes2HexString(flagBuffer);
                    Log.d(TAG, "接收标识数据：" + flag);

                    //连续多次快速按下语音键，移除上次即将播放的音频
                    mHandler.removeMessages(Cons.HANDLER_AUTO_PLAY_WAV_VOICE);

                    if (Arrays.equals(VOICE_RECEIVE_START, flagBuffer)) {
                        //创建语音目录及文件
                        if (createVoiceDirectory()) {
                            if (!createVoiceFile()) {
                                Log.e(TAG, "语音文件创建失败!");
                                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "语音文件创建失败!");
                            }
                        } else {
                            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "语音目录创建失败!");
                            return;
                        }

                        Log.d(TAG, "初始化语音解码器...");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "初始化语音解码器...", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);

                        //初始化解码器
                        MyJni.initDecode(voicePcmFilePath, null);
                        Log.d(TAG, "开始接收语音数据...");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "开始接收语音数据...", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);

                    } else if (Arrays.equals(VOICE_RECEIVE_END, flagBuffer)) {
                        Log.d(TAG, "语音数据接收结束！");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "语音数据接收结束！", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);

                        //完成解码
                        MyJni.finishDecode();
                        Log.d(TAG, "完成语音数据解码！");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "完成语音数据解码！", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);

                        if(voicePcmFilePath == null || voiceWavFilePath ==null){
                            return;
                        }

                        //将解码后的pcm格式的语音文件转换成wav格式语音文件
                        PcmToWavUtil pcmToWavUtil = new PcmToWavUtil();
                        pcmToWavUtil.pcmToWav(voicePcmFilePath,voiceWavFilePath);

                        //延时1s,自动播放语音
                        Message message = new Message();
                        message.what = Cons.HANDLER_AUTO_PLAY_WAV_VOICE;
                        mHandler.sendMessageDelayed(message,500);
                    }
                    break;

                case Cons.HANDLER_RECEIVE_MESS_SUCCESS:  ///接收语音数据
                    byte[] messBuffer = (byte[]) msg.obj;
                    String mess = TypeConversion.bytes2HexString(messBuffer);
                    Log.d(TAG, "接收语音数据，长度：" + messBuffer.length + ",数据：" + mess);

                    //保存语音数据进.txt文件
                    saveByteVoiceDataToTxtFile(messBuffer);

                    //ADPCM解码语音数据
                    MyJni.decodeByByteM1(messBuffer);

                    break;

                case Cons.HANDLER_AUTO_PLAY_WAV_VOICE:  //播放解码后的语音数据
                    if(voiceWavFilePath == null){
                        Log.e(TAG, "当前没有可播放的语音文件！");
                        ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "当前没有可播放的语音文件!");
                        return;
                    }
                    Log.d(TAG, "voiceWavFilePath = " + voiceWavFilePath);
                    if(voicePlay == null){
                        voicePlay = new VoicePlay();
                    }
                    voicePlay.setLocalAudioFilePath(voiceWavFilePath);
                    voicePlay.setOnPlayStateListener(onPlayStateListener);
                    voicePlay.start();

                    Log.d(TAG, "语音播放中...");
                    ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "语音播放中...",Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);
                    break;
            }
        }
    };

    //语音播报结束
    private VoicePlay.OnPlayStateListener onPlayStateListener = new VoicePlay.OnPlayStateListener() {
        @Override
        public void onPlayCompletion() {
            Log.d(TAG, "语音播放结束");
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "语音播放结束",Cons.UI_STRING_NOTIFY_LEVEL_INFO);
        }
    };

    /**
     * 该构造方法无需显性调用，绑定服务的时候自动调用
     */
    public VoiceService() {
        Log.d(TAG, "VoiceService():");

        //创建Messenger并传入ServiceHandler实例对象
        serviceMessenger = new Messenger(serviceHandler);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate():");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        // 当绑定Service时,该方法被调用,将通过messenger返回一个实现 * IBinder接口的实例对象
        if (intent == null) {
            Log.e(TAG, "onBind():intent == null");
            return null;
        } else {
            Log.d(TAG, "onBind():return * IBinder");
            return serviceMessenger.getBinder();
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind():");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy():");
        //服务异常断开时，记得断开设备连接
        if (isConnected) {
            disConnectDevice();
        }
    }

    public void initBluetooth(boolean btType) {
        Log.d(TAG, "初始化蓝牙");
        //服务绑定成功之后，初始化蓝牙操作
        btBluetooth = BTBluetooth.getInstance();
        btBluetooth.init(getApplicationContext(), btType);
        //设置配对状态监听
        btBluetooth.setOnBindStateChangeListener(onBindStateChangeListener);
        //设置系统蓝牙状态监听
        btBluetooth.setOnBluetoothStateChangeListener(onBluetoothStateChangeListener);
    }

    /**
     * 变量复位
     */
    private void initParams(){
        isConnected = false;
        isBounded = false;
        isAppDisConnect = false;
        isAppDisBound = false;
        isSysBtClose = false;
        isStartVoiceOk = false;
    }

    /**
     * 扫描设备
     */
    private void scanDevice() {
        //扫描之前检查是否已有连接设备
        if (btBluetooth != null) {
            if (isConnected) {
                //先断开连接，再解除配对
                disConnectDevice();
            }
            //如果系统已有配对设备，先解除配对
            List<BluetoothDevice> bondList = btBluetooth.getBoundDeviceList();
            for (int i = 0; i < bondList.size(); i++) {
                btBluetooth.disConnectHidDevice(bondList.get(i));
                disPairDevice(bondList.get(i));
            }
            btBluetooth.discoveryDevice(onSearchListener, Cons.SCAN_OUT_TIME);  //扫描时长 1min
        } else {
            Log.e(TAG, "scanDevice(): btBluetooth == null");
        }
    }

    /**
     * 停止扫描
     */
    private void stopScanDevice() {
        if (btBluetooth != null) {
            btBluetooth.stopDiscoveryDevice();
        } else {
            Log.e(TAG, "stopScanDevice(): btBluetooth == null");
        }
    }

    /**
     * 配对
     */
    private void pairDevice(BluetoothDevice bluetoothDevice) {
        if (btBluetooth != null) {
            btBluetooth.boundDevice(bluetoothDevice);
            //设置配对15s超时
            mHandler.postDelayed(pairRunnable, Cons.PAIR_OUT_TIME);
        } else {
            Log.e(TAG, "pairDevice(): btBluetooth == null");
        }
    }

    //配对超时
    private Runnable pairRunnable = new Runnable() {
        @Override
        public void run() {
            if (btBluetooth != null) {
                List<BluetoothDevice> bondList = btBluetooth.getBoundDeviceList();
                for (int i = 0; i < bondList.size(); i++) {
                    btBluetooth.disConnectHidDevice(bondList.get(i));
//                    disPairDevice(bondList.get(i));
                }

                Log.d(TAG, "配对超时!");
                //通知客户端 配对超时
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "配对超时");

            }

        }
    };


    /**
     * 解除配对
     */
    private void disPairDevice(BluetoothDevice bluetoothDevice) {
        if (btBluetooth != null) {
            isAppDisBound = true;
            btBluetooth.disBoundDevice(bluetoothDevice);
        } else {
            Log.e(TAG, "disPairDevice(): btBluetooth == null");
        }
    }

    /**
     * 连接设备
     */
    private void connectDevice(BluetoothDevice bluetoothDevice) {
        if (btBluetooth != null) {
            btBluetooth.connectBLEDevice(true,
                    Cons.SERVICE_UUID,
                    new String[]{Cons.NOTIFY_FLAG_UUID, Cons.NOTIFY_MESS_UUID},
                    Cons.WRITE_FLAG_UUID,
                    bluetoothDevice, Cons.CONNECT_OUT_TIME, onConnectListener);
        } else {
            Log.e(TAG, "connectDevice(): btBluetooth == null");
        }
    }

    /**
     * 断开连接：1、先断开GATT连接  2、断开连接回调处，解除配对
     */
    private void disConnectDevice() {
        if (btBluetooth != null) {
            isAppDisConnect = true;
            btBluetooth.disConnectDevice();
        } else {
            Log.e(TAG, "disConnectDevice(): btBluetooth == null");
        }
    }

    /**
     * 发送数据
     */
    private void sendMsgToDevice(byte[] data) {
        if (!isConnected) {
            Log.e(TAG, "sendMsg(): isConnected = false");
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "数据通讯异常—连接已断开");
            return;
        }
        if (btBluetooth != null) {
            boolean isSuc = btBluetooth.sendData(data);
            if (!isSuc) {
                Log.e(TAG, "sendMsg(): 发送数据操作失败");
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "数据通讯异常—发送数据操作失败");
//                disConnectDevice();
            }
        } else {
            Log.e(TAG, "sendMsg(): btBluetooth == null");
        }
    }

    //系统蓝牙状态回调
    private OnBluetoothStateChangeListener onBluetoothStateChangeListener = new OnBluetoothStateChangeListener() {
        @Override
        public void onBluetoothOpen() {
            Log.w(TAG, "系统蓝牙已打开");
            //延时2s,确保系统蓝牙有足够的反应时间
            HandlerUtil.sendEmptyMsgDelayed(mHandler, Cons.HANDLER_BT_OPENED, 2000);
        }

        @Override
        public void onBluetoothOpening() {

        }

        @Override
        public void onBluetoothClose() {
            Log.w(TAG, "系统蓝牙已关闭");
            HandlerUtil.sendEmptyMsg(mHandler, Cons.HANDLER_BT_CLOSED);
        }

        @Override
        public void onBluetoothClosing() {

        }
    };

    /**
     * 扫描结果回调
     */
    private OnSearchListener onSearchListener = new OnSearchListener() {
        @Override
        public void onDiscoveryStart() {

        }

        @Override
        public void onDiscoveryStop() {
            Log.d(TAG, "扫描结束");
            // 向客户端发送 扫描结束
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_SCAN_FINISHED);
        }

        @Override
        public void onDeviceFound(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
            SearchDevice searchDevice = new SearchDevice(bluetoothDevice, i, bytes);
            Log.e(TAG,"onDeviceFound:"+bluetoothDevice.toString());
            // 向客户端发送 扫描到设备结果
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_SCAN_DEVICE, searchDevice);

        }

        @Override
        public void onDeviceSearchOutTime() {
            Log.e(TAG, "扫描超时");
            // 向客户端发送 扫描超时（即扫描不到设备）
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_SCAN_OUT_TIME);

        }
    };

    //配对状态回调
    private OnBindStateChangeListener onBindStateChangeListener = new OnBindStateChangeListener() {
        @Override
        public void onBondNone() {
            isBounded = false;
            Log.w(TAG, "解除配对成功");
            //延时2s,确保系统蓝牙有足够的反应时间
            HandlerUtil.sendEmptyMsgDelayed(mHandler, Cons.HANDLER_DIS_PAIR_SUCCESS, 2000);
        }

        @Override
        public void onBonding() {

        }

        @Override
        public void onBonded() {
            isBounded = true;
            Log.w(TAG, "配对成功");
            //延时2s,确保系统蓝牙有足够的反应时间
            HandlerUtil.sendEmptyMsgDelayed(mHandler, Cons.HANDLER_PAIR_SUCCESS, 2000);
        }
    };

    //连接回调
    private OnConnectListener onConnectListener = new OnConnectListener() {
        @Override
        public void onStartConnect() {
        }

        @Override
        public void onConnectSuccess() {
            isConnected = true;
            Log.w(TAG, "连接成功");
            HandlerUtil.sendEmptyMsg(mHandler, Cons.HANDLER_CONNECT_SUCCESS);
        }

        @Override
        public void onConnectFailure(String exception, int status) {
            isConnected = false;
            String failMess = exception + "!-- status = " + status;
            Log.e(TAG, failMess);
            // 向客户端发送 连接失败
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, failMess);
        }

        @Override
        public void onDisConnectSuccess(int statue) {
            isConnected = false;
            Log.w(TAG, "断开连接成功 statue = " + statue);
            if (isAppDisConnect) {  //APP主动断开连接 ，还需要解除配对
                isAppDisConnect = false;
                HandlerUtil.sendEmptyMsg(mHandler,Cons.HANDLER_DISCONNECT_SUCCESS);

            } else {  //设备异常断开
                // 向客户端发送 设备已断开
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "设备已主动断开：" + statue);
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_PAIR_CONNECT_STATE,false);
            }


        }

        @Override
        public void onSendSuccess(byte[] data) {
            Log.w(TAG, "成功发送数据 = " + TypeConversion.bytes2HexString(data, data.length));
            if (Arrays.equals(data, CHANGE_HID_GATT)) {
                //成功发送O1
                HandlerUtil.sendEmptyMsg(mHandler, Cons.HANDLER_SEND_CHANGE_HID_GATT_SUCCESS);
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_UI_STRING_NOTIFY, "发送成功", Cons.UI_STRING_NOTIFY_LEVEL_DEBUG);
            }
        }

        @Override
        public void onSendError(byte[] data, String errorMsg) {
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "数据通讯异常—发送数据回调失败");
//            disConnectDevice();
        }

        @Override
        public void onReceiveSuccess(BluetoothGattCharacteristic characteristic, byte[] buffer) {
//            Log.w(TAG, "成功接收数据 = " + TypeConversion.bytes2HexString(buffer, buffer.length));
            if (characteristic.getUuid().toString().equals(Cons.NOTIFY_FLAG_UUID)) {
                //标识
                HandlerUtil.sendMsg(mHandler, Cons.HANDLER_RECEIVE_FLAG_SUCCESS, buffer);

            } else if (characteristic.getUuid().toString().equals(Cons.NOTIFY_MESS_UUID)) {
                //语音数据
                HandlerUtil.sendMsg(mHandler, Cons.HANDLER_RECEIVE_MESS_SUCCESS, buffer);
            }
        }

        @Override
        public void onReceiveError(String errorMsg) {
            // 向客户端发送 接收数据失败
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "数据通讯异常—接收数据失败");
            disConnectDevice();
        }

        @Override
        public void onMTUSetSuccess(String successMTU, int newMTU) {
            if (newMTU >= packetMaxLen) {  //i > packetMaxLen 不可能出现！
                Log.d(TAG, "申请成功，新的MTU = " + newMTU);
                // 修改MTU成功
                HandlerUtil.sendEmptyMsg(mHandler, Cons.HANDLER_SET_MTU_SUCCESS);

            } else {  // i <  packetMaxLen ,申请的MTU超出最大值
                // 向客户端发送 修改MTU成功 ,保存新的MTU值
                Log.e(TAG, "申请的MTU溢出，最大值 = " + newMTU);
                ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, "申请的MTU溢出，最大值 = " + newMTU);
                disConnectDevice();
            }
        }

        @Override
        public void onMTUSetFailure(String failMTU) {
            // 向客户端发送 修改MTU失败
            ServerClientUtil.sendToClientMsg(clientMessenger, Cons.MSG_REPO_ERROR, failMTU);
            disConnectDevice();
        }
    };

    /**
     * 创建语音目录，存放形式.txt 和 .wav 文件
     * /storage/emulated/0/AVoiceControl/时间+voices
     */
    private boolean createVoiceDirectory() {
        String curTime = TimeUtil.getCurTimeWithYear().replace(" ", "_");
        voiceDirectoryPath = Cons.PATH_VOICE_LOCAL + "/" + curTime + "voices";
        //创建存储目录
        boolean b = FileUtil.createOrExistsDir(voiceDirectoryPath);
        if (b) {
            Log.d(TAG, "语音目录已存在：" + voiceDirectoryPath);
            return true;
        } else {
            Log.d(TAG, "语音目录创建失败：" + voiceDirectoryPath);
            return false;
        }
    }

    /**
     * 创建语音文件 .txt 和 .wav
     */
    private boolean createVoiceFile() {
        voiceTxtFilePath = voiceDirectoryPath + "/" + "voiceTxtData.txt";
        voicePcmFilePath = voiceDirectoryPath + "/" + "voicePcmData.pcm";
        voiceWavFilePath = voiceDirectoryPath + "/" + "voiceWavData.wav";
        voiceTxtFile = new File(voiceTxtFilePath);
        voicePcmFile = new File(voicePcmFilePath);
        voiceWavFile = new File(voiceWavFilePath);

//        preVoicePcmFilePath = voiceDirectoryPath + "/" + "preVoicePcmData.pcm";
//        preVoicePcmFile = new File(preVoicePcmFilePath);

        boolean isCreateTxtFile = FileUtil.createOrExistsFile(voiceTxtFile);
        boolean isCreatePcmFile = FileUtil.createOrExistsFile(voicePcmFile);
        boolean isCreateWavFile = FileUtil.createOrExistsFile(voiceWavFile);

//        boolean isCreatePrePcmFile = FileUtil.createOrExistsFile(preVoicePcmFile);

        if (isCreateTxtFile && isCreatePcmFile && isCreateWavFile) {
            Log.d(TAG, "语音文件.txt 、.pcm、 .wav全部创建成功！");
            return true;
        } else {
            Log.e(TAG, "语音文件.txt 、.pcm、.wav创建失败！");
            return false;
        }
    }

    /**
     * 保存byte[]语音数据到本地.txt文件
     */
    private void saveByteVoiceDataToTxtFile(byte[] data){
        if(FileUtil.isFileExists(voiceTxtFile)){ //文件存在
            // 创建FileOutputStream对象
            FileOutputStream outputStream = null;
            // 创建BufferedOutputStream对象
            BufferedOutputStream bufferedOutputStream = null;
            try {
                // 获取FileOutputStream对象
                outputStream = new FileOutputStream(voiceTxtFile,true);
                // 获取BufferedOutputStream对象
                bufferedOutputStream = new BufferedOutputStream(outputStream);
                // 往文件所在的缓冲输出流中写byte数据
                bufferedOutputStream.write(data);
                // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
                bufferedOutputStream.flush();
            } catch (Exception e) {
                // 打印异常信息
                e.printStackTrace();
            } finally {
                // 关闭创建的流对象
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bufferedOutputStream != null) {
                    try {
                        bufferedOutputStream.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }
    }


}
